<h1 id="duktapebuiltins">Duktape built-ins</h1>

<p>This section summarizes Duktape-specific and non-ECMAScript built-in
objects, methods, and values.</p>

<h2>Additional global object properties</h2>

<table>
<thead>
<tr>
<th>Property</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="propname"><a href="#builtin-global">globalThis</a></td>
<td>References the global object itself.
    See <a href="https://github.com/tc39/proposal-global">proposal-global</a>.</td>
</tr>
<tr>
<td class="propname"><a href="#builtin-duktape">Duktape</a></td>
<td>The Duktape built-in object.  Contains miscellaneous implementation specific stuff.</td>
</tr>
<tr>
<td class="propname"><a href="#builtin-cbor">CBOR</a></td>
<td>Experimental <a href="http://cbor.io/">CBOR</a> API based on <a href="https://github.com/paroga/cbor-js">cbor-js</a>.</td>
</tr>
<tr>
<td class="propname"><a href="#builtin-textencoder">TextEncoder</a></td>
<td>TextEncoder() from <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding API</a>.
    Converts a string into a buffer using UTF-8 encoding.</td>
</tr>
<tr>
<td class="propname"><a href="#builtin-textdecoder">TextDecoder</a></td>
<td>TextDecoder() from <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding API</a>.
    Converts a buffer into a string using UTF-8 encoding.</td>
</tr>
<tr>
<td class="propname"><a href="#builtin-performance">performance</a></td>
<td>performance.now() from <a href="https://www.w3.org/TR/hr-time/#dom-performance-now">High Resolution Time Level 2</a>.
    Bindings like performance.timing from
    <a href="https://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute">Navigation Timing</a>
    are not supported.</td>
</tr>
</tbody>
</table>

<h2 id="builtin-global">globalThis</h2>

<p>References the global object itself, see
<a href="https://github.com/tc39/proposal-global">proposal-global</a>.
(The binding was initially named 'global' but this was changed due to
some web sites breaking.).</p>

<h2 id="builtin-duktape">The Duktape object</h2>

<table>
<thead>
<tr>
<th>Property</th><th>Description</th>
</tr>
</thead>
<tbody>
<tr><td class="propname"><a href="#builtin-duktape-version">version</a></td>
    <td>Duktape version number: <code>(major * 10000) + (minor * 100) + patch</code>.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-env">env</a></td>
    <td>Cryptic, version dependent summary of most important effective options like endianness and architecture.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-fin">fin</a></td>
    <td>Set or get finalizer of an object.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-enc">enc</a></td>
    <td>Encode a value (hex, base-64, JX, JC): <code>Duktape.enc('hex', 'foo')</code>.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-dec">dec</a></td>
    <td>Decode a value (hex, base-64, JX, JC): <code>Duktape.dec('base64', 'Zm9v')</code>.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-info">info</a></td>
    <td>Get internal information (such as heap address and alloc size)
        of a value in a version specific format.  The C API equivalent
        is <code>duk_inspect_value()</code>.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-act">act</a></td>
    <td>Get information about call stack entry.  The C API equivalent
        is <code>duk_inspect_callstack_entry()</code>.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-gc">gc</a></td>
    <td>Trigger mark-and-sweep garbage collection.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-compact">compact</a></td>
    <td>Compact the memory allocated for a value (object).</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-errcreate-errthrow">errCreate</a></td>
    <td>Callback to modify/replace a created error.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-errcreate-errthrow">errThrow</a></td>
    <td>Callback to modify/replace an error about to be thrown.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-pointer">Pointer</a></td>
    <td>Pointer constructor (function).</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-thread">Thread</a></td>
    <td>Thread constructor (function).</td></tr>
</tbody>
</table>

<h3 id="builtin-duktape-version">version</h3>

<p>The <code>version</code> property allows version-based feature detection and
behavior.  Version numbers can be compared directly: a logically higher version
will also be numerically higher.  For example:</p>
<pre class="ecmascript-code">
if (typeof Duktape !== 'object') {
    print('not Duktape');
} else if (Duktape.version &gt;= 20403) {
    print('Duktape 2.4.3 or higher');
} else if (Duktape.version &gt;= 10500) {
    print('Duktape 1.5.0 or higher (but lower than 2.4.3)');
} else {
    print('Duktape lower than 1.5.0');
}
</pre>

<p>The value of <code>version</code> for pre-releases is one less than the
actual release, e.g. 1199 for a 0.12.0 pre-release and 10299 for a 1.3.0
pre-release.  See <a href="#versioning">Versioning</a>.</p>

<p>Remember to check for existence of <code>Duktape</code> when doing feature
detection.  Your code should typically work on as many engines as possible.
Avoid the common pitfall of using a direct identifier reference in the check:</p>
<pre class="ecmascript-code">
// Bad idea: ReferenceError if missing
if (!Duktape) {
    print('not Duktape');
}

// Better: check through 'this' (bound to global)
if (!this.Duktape) {
    print('not Duktape');
}

// Better: use typeof to check also type explicitly
if (typeof Duktape !== 'object') {
    print('not Duktape');
}
</pre>

<h3 id="builtin-duktape-env">env</h3>

<p><code>env</code> summarizes the most important effective compile options
in a version specific, quite cryptic manner.  The format is version specific
and is not intended to be parsed programmatically.  This is mostly useful for
developers (see <code>duk_hthread_builtins.c</code> for the code which sets
the value).</p>

<p>Example from Duktape 1.1.0:</p>
<pre class="ecmascript-code">
ll u n p2 a4 x64 linux gcc     // l|b|m integer endianness, l|b|m IEEE double endianness
                               // p|u packed/unpacked tval
                               // n|various, memory optimization options (n = none)
                               // p1|p2|p3 prop memory layout
                               // a1|a4|a8: align target
                               // x64|x86|arm|etc: architecture
                               // linux|windows|etc: operating system
                               // gcc|clang|msvc|etc: compiler
</pre>

<p>For endianness, "l" stands for little endian, "b" for big endian, and "m"
for mixed endian (legacy ARM devices, see e.g.
<a href="http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0056d/Bcfhgcgd.html">The FPA architecture</a>).</p>

<h3 id="builtin-duktape-fin">fin()</h3>

<p>When called with a single argument, gets the current finalizer of an object:</p>
<pre class="ecmascript-code">
var currFin = Duktape.fin(o);
</pre>

<p>When called with two arguments, sets the finalizer of an object (returns undefined):</p>
<pre class="ecmascript-code">
Duktape.fin(o, function(x) { print('finalizer called'); });
Duktape.fin(o, undefined);  // disable
</pre>

<h3 id="builtin-duktape-enc">enc()</h3>

<p><code>enc()</code> encodes its argument value into chosen format.
The first argument is a format (currently supported are "hex", "base64",
"jx" and "jc"), second argument is the value to encode, and any further
arguments are format specific.</p>

<!-- XXX: maybe remove support for non-buffer inputs? -->
<p>For "hex" and "base64", buffer values are encoded as is, other values
are string coerced and the internal byte representation (extended UTF-8)
is then encoded.  The result is a string.  For example, to encode a string
into base64:</p>
<pre class="ecmascript-code">
var result = Duktape.enc('base64', 'foo');
print(result);  // prints 'Zm9v'
</pre>

<p>For "jx" and "jc" the argument list following the format name is the
same as for <code>JSON.stringify()</code>: value, replacer (optional),
space (optional).  For example:</p>
<pre class="ecmascript-code">
var result = Duktape.enc('jx', { foo: 123 }, null, 4);
print(result);  // prints JX encoded {foo:123} with 4-space indent
</pre>

<h3 id="builtin-duktape-dec">dec()</h3>

<p><code>dec()</code> provides the reverse function of <code>enc()</code>.</p>

<p>For "hex" and "base64" the input value is first string coerced (it only
really makes sense to decode strings).  The result is always a plain buffer.
For example:</p>
<pre class="ecmascript-code">
var result = Duktape.dec('base64', 'Zm9v');
print(typeof result, result);  // prints 'object foo'
</pre>

<p>If you prefer a full <code>Uint8Array</code> over a plain buffer, you can
coerce the result as follows:</p>
<pre class="ecmascript-code">
var result = Object(Duktape.dec('base64', 'Zm9v'));
print(typeof result, result);  // prints 'object foo'
</pre>

<p>If you wish to get back a string value, you can coerce the plain buffer to
a string e.g. as follows:</p>
<pre class="ecmascript-code">
// Use TextDecoder which decodes the input as UTF-8.  You can also use
// the Node.js Buffer binding to achieve a similar result.

var result = new TextDecoder().decode(Duktape.dec('base64', 'Zm9v'));
print(typeof result, result);  // prints 'string foo'
</pre>

<p>For "jx" and "jc" the argument list following the format name is the same
as for <code>JSON.parse()</code>: text, reviver (optional).  For example:</p>
<pre class="ecmascript-code">
var result = Duktape.dec('jx', "{foo:123}");
print(result.foo);  // prints 123
</pre>

<h3 id="builtin-duktape-info">info()</h3>

<p><code>Duktape.info()</code> returns an object exposing internal information
related to its argument value.  See
<code><a href="api.html#duk_inspect_value">duk_inspect_value()</a></code>
for description of current fields.</p>

<div class="note">
The properties of the result object are not under versioning guarantees and may
change in an incompatible fashion even in minor versions (but not patch versions).
</div>

<h3 id="builtin-duktape-act">act()</h3>

<p>Get information about a call stack entry.  Takes a single number argument
indicating depth in the call stack: -1 is the top (innermost) entry, -2 is the
one below that etc.  Returns an object describing the call stack entry, or
<code>undefined</code> if the entry doesn't exist.  See
<code><a href="api.html#duk_inspect_callstack_entry">duk_inspect_callstack_entry()</a></code>
for description of current fields.</p>

<div class="note">
The properties of the result object are not under versioning guarantees and may
change in an incompatible fashion even in minor versions (but not patch versions).
</div>

<p>Example:</p>
<pre class="ecmascript-code">
function dump() {
    var i, t;
    for (i = -1; ; i--) {
        t = Duktape.act(i);
        if (!t) { break; }
        print(i, t.lineNumber, t.function.name, Duktape.enc('jx', t));
    }
}

dump();
</pre>

<p>The example, when executed with the command line tool, currently prints
something like:</p>
<pre>
-1 0 act {lineNumber:0,pc:0,function:{_func:true}}
-2 4 dump {lineNumber:4,pc:16,function:{_func:true}}
-3 10 global {lineNumber:10,pc:5,function:{_func:true}}
</pre>

<p>The interesting entries are <code>lineNumber</code> and <code>function</code>
which provides e.g. the function name.</p>

<p>You can also implement a helper to get the current line number using
<code>Duktape.act()</code>:</p>
<pre class="ecmascript-code">
function getCurrentLine() {
    'use duk notail';

    /* Tail calls are prevented to ensure calling activation exists.
     * Call stack indices: -1 = Duktape.act, -2 = getCurrentLine, -3 = caller
     */

    var a = Duktape.act(-3) || {};
    return a.lineNumber;
}
print('running on line:', getCurrentLine());
</pre>

<h3 id="builtin-duktape-gc">gc()</h3>

<p>Trigger a forced mark-and-sweep collection.  The call takes an optional
integer flags field, see <code>duktape.h</code> for constants.</p>

<!-- Return value is undocumented for now, which is probably good for now.
     Not sure what the best return value would be.
-->

<h3 id="builtin-duktape-compact">compact()</h3>

<p>Minimize the memory allocated for a target object.  Same as the C API call
<code>duk_compact()</code> but accessible from ECMAScript code.  If called with
a non-object argument, this call is a no-op.  The argument value is returned by
the function, which allows code such as:</p>
<pre class="ecmascript-code">
var obj = {
    foo: Duktape.compact({ bar: 123 })
}
</pre>

<p>This call is useful when you know that an object is unlikely to gain new
properties, but you don't want to seal or freeze the object in case it does.</p>

<h3 id="builtin-duktape-errcreate-errthrow">errCreate() and errThrow()</h3>

<p>These can be set by user code to process/replace errors when they are created
(<code>errCreate</code>) or thrown (<code>errThrow</code>).  Both values are
initially non-existent.</p>

<p>See
<a href="#error-handlers">Error handlers (errCreate and errThrow)</a> for
details.</p>

<h2 id="builtin-duktape-pointer">Duktape.Pointer (constructor)</h2>

<table>
<thead>
<tr>
<th>Property</th><th>Description</th>
</tr>
</thead>
<tbody>
<tr><td class="propname">prototype</td><td>Prototype for Pointer objects.</td></tr>
</tbody>
</table>

<p>The Pointer constructor is a function which can be called both as an
ordinary function and as a constructor:</p>
<ul>
<li>When called as a function, coerces the first argument to a pointer using
    the custom <code>ToPointer</code> coercion.  The return value is a plain
    pointer (not a Pointer object).</li>
<li>When called as a constructor, coerces the first argument to a pointer
    using the custom <code>ToPointer</code> coercion.  Returns a Pointer object
    whose internal value is the pointer resulting from the coercion.  The
    internal prototype of the newly created Pointer will be the
    <code>Duktape.Pointer.prototype</code> object.</li>
</ul>

<h2>Duktape.Pointer.prototype</h2>

<table>
<thead>
<tr>
<th>Property</th><th>Description</th>
</tr>
</thead>
<tbody>
<tr><td class="propname">toString</td><td>Convert Pointer to a printable string.</td></tr>
<tr><td class="propname">valueOf</td><td>Return the primitive pointer value held by Pointer.</td></tr>
</tbody>
</table>

<p><code>toString()</code> and <code>valueOf</code> accept both plain pointers and
Pointer objects as their <code>this</code> binding.  This allows code such as:</p>
<pre class="ecmascript-code">
var plain_ptr = Duktape.Pointer({ test: 'object' });
print(plain_ptr.toString());
</pre>

<h2 id="builtin-duktape-thread">Duktape.Thread (constructor)</h2>

<table>
<thead>
<tr>
<th>Property</th><th>Description</th>
</tr>
</thead>
<tbody>
<tr><td class="propname">prototype</td><td>Prototype for Thread objects.</td></tr>
<tr><td class="propname">resume</td><td>Resume target thread with a value or an error.
Arguments: target thread, value, flag indicating whether value is to be thrown (optional, default false).</td></tr>
<tr><td class="propname">yield</td><td>Yield a value or an error from current thread.
Arguments: value, flag indicating whether value is to be thrown (optional, default false).</td></tr>
<tr><td class="propname">current</td><td>Get currently running Thread object.</td></tr>
</tbody>
</table>

<p>The Thread constructor is a function which can be called both as an
ordinary function and as a constructor.  The behavior is the same in both
cases:</p>
<ul>
<li>The first argument is checked to be a function (if not, a <code>TypeError</code>
    is thrown).  The function must be an ECMAScript function (bound or non-bound).
    The return value is a new thread whose initial function is recorded to be the
    argument function (this function will start executing when the new thread is
    first resumed).  The internal prototype of the newly created Thread will be the
    <code>Duktape.Thread.prototype</code> object.</li>
</ul>

<h2>Duktape.Thread.prototype</h2>

<table>
<thead>
<tr>
<th>Property</th><th>Description</th>
</tr>
</thead>
<tbody>
<tr><td colspan="2">No properties at the moment.</td></tr>
</tbody>
</table>

<h2 id="builtin-cbor">CBOR</h2>

<p>CBOR (Concise Binary Object Representation) is a compact binary encoding
for arbitrary structured values.  It is faster than JSON and can encode some
ECMAScript values more accurately.  It is suitable as an alternative to JSON
for state serialization, IPC, etc.  See:</p>
<ul>
<li><a href="http://cbor.io/">CBOR &#8212; Concise Binary Object Representation (cbor.io)</a></li>
<li><a href="https://tools.ietf.org/html/rfc7049">Concise Binary Object Representation (CBOR) (RFC 7049)</a></li>
</ul>

<p>The <code>CBOR</code> object provides encode/decode functions to convert
arbitrary ECMAScript values to CBOR and vice versa.  There's no official
CBOR API yet, so the API is based, for now, on
<a href="https://github.com/paroga/cbor-js">cbor-js</a>.
There's also a <a href="api.html#taglist-cbor">C API for CBOR</a>.</p>

<div class="note">
The binding is currently experimental, and details are likely to change over
time.  For example, custom CBOR tags are being registered to serialize ECMAScript
values more accurately.
</div>

<p>Example:</p>

<pre class="ecmascript-code">
var enc = CBOR.encode([ 'foo', 'bar', { quux: true } ]);
print(Duktape.enc('hex', enc));  // = 8363666f6f63626172a16471757578f5
var dec = CBOR.decode(enc);
print(Duktape.enc('jx', dec));   // = ["foo","bar",{quux:true}]
</pre>

<h2 id="builtin-textencoder">TextEncoder</h2>

<p>TextEncoder() is part of the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding API</a>
and provides a clean way of encoding a string into a buffer (Uint8Array)
using UTF-8 encoding.  Surrogate pairs are combined during the process.
For example:</p>

<pre class="ecmascript-code">
var str = '\u{1f4a9}';                   // non-BMP codepoint
print(str.length);                       // length is 2, represented as a surrogate pair
var u8 = new TextEncoder().encode(str);
print(u8.length);                        // length is 4, a single UTF-8 codepoint
print(Duktape.enc('jx', u8));            // |f09f92a9|, UTF-8 bytes F0 9F 92 A9
</pre>

<h2 id="builtin-textdecoder">TextDecoder</h2>

<p>TextDecoder() is part of the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding API</a>
and provides a clean way of decoding a buffer into a string using UTF-8
encoding.  Non-BMP codepoints are represented as surrogate pairs in the
resulting string.  For example:</p>

<pre class="ecmascript-code">
var u8 = new Uint8Array([ 0xf0, 0x9f, 0x92, 0xa9 ]);  // a single non-BMP codepoint
var str = new TextDecoder().decode(u8);
print(str.length);                       // length is 2, represented as a surrogate pair
print(str.charCodeAt(0));                // 55357, high surrogate
print(str.charCodeAt(1));                // 56489, low surrogate
</pre>

<h2 id="builtin-performance">performance</h2>

<p>performance.now() provides a monotonic time in milliseconds (including
fractions if available) from an unspecified origin.  The return value is
from DUK_USE_GET_MONOTONIC_TIME() with a fallback to DUK_USE_DATE_GET_NOW().
If an actual monotonic time provider is available, the return value is
guaranteed to advance in real time without "time jumps" caused by date/time
adjustments.  This is useful for performance measurement, scheduling events
relative to current time instead of wall clock time, rate limiting, etc.
Example:</p>

<pre class="ecmascript-code">
function testFunction() {
    for (var i = 0; i &lt; 1e6; i++) {}
}

var t1 = performance.now();
testFunction();
var t2 = performance.now();
print('test took:', (t2 - t1), 'milliseconds');
</pre>

<p>performance.timeOrigin is currently (Duktape 2.2.0) absent on purpose,
until its semantics for Duktape are decided.</p>

<p><a href="https://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute">Navigation Timing</a>
bindings like performance.timing are not currently supported.</p>
